package detector.audio;

import detector.audio.processing.AudioListener;
import detector.audio.processing.Monitor;
import android.content.Context;
import android.app.*;
import android.util.AttributeSet;
import android.widget.ProgressBar;
import detector.audio.*;

/**
 * A bar that displays the audio level.
 * 
 * @author Kyle
 *
 */
public class MonitorBar extends ProgressBar {
	
	MonitorBar thisBar = this;
	private boolean isEnabled;
	private static short maxValue = 0;	//Tracks the max received audio value so far to use for windowing
   	//the audio meter
	
	public MonitorBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		isEnabled = true;
		//Subscribe to audio events
		Monitor.getMonitor().addAudioListener(new AudioListener() {
			public void onAudioLevelReceived(final short level) {
				//Perform on UI thread - must call this since this method gets
				//called from a different thread
				//Only update if enabled
				if (isEnabled) {
					((Activity)thisBar.getContext()).runOnUiThread(new Runnable() {
						public void run() {
							if (level > maxValue) {
								maxValue = level;
								thisBar.setMax(maxValue);
							}
							thisBar.setProgress(level);
						}
					});
				} else {
					thisBar.setProgress(0);
				}
			}
		});
	}
	
	public MonitorBar(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		
	}
	
	@Override
	/**
	 * If true, displays audio level. If false, is just always empty
	 */
	public void setEnabled(boolean isEnabled) {
		this.isEnabled = isEnabled;
	}
}
